﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WJ.Infrastructure.Data;
using WJ.Infrastructure.DDD;
using WJ.Infrastructure.EntitiesExtension;

namespace WJ.Infrastructure.EF
{
    public static class QueryExtension
    {
        public static TEntity GetOne<TEntity>(this EFContext dbcontext, Expression<Func<TEntity, bool>> exp) where TEntity : class, IEntity
        {
            return dbcontext.Set<TEntity>()
                .FirstOrDefault(exp.ByVisible());
        }

        public static PageData<TEntity> GetList<TEntity>(this EFContext dbcontext, Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal)
            where TEntity : class, IEntity
        {
            return dbcontext.Set<TEntity>()
                  .WhereByVisible(exp)
                  .OrderByDescending(t => t.Id)
                  .ListPager(pagesize, pageindex, istotal);
        }

        public static List<TEntity> GetList<TEntity>(this EFContext dbcontext, Expression<Func<TEntity, bool>> exp)
            where TEntity : class, IEntity
        {
            return dbcontext.Set<TEntity>()
                .WhereByVisible(exp).ToList();
        }

        public static IQueryable<TEntity> GetListQuery<TEntity>(this EFContext dbcontext,Expression<Func<TEntity, bool>> exp)
            where TEntity : class, IEntity
        {
            return dbcontext.Set<TEntity>()
                .WhereByVisible(exp);
        }

        public static bool Exists<TEntity>(this EFContext dbcontext, Expression<Func<TEntity, bool>> exp)
            where TEntity : class, IEntity
        {
            return dbcontext.Set<TEntity>()
                .Any(exp.ByVisible());
        }

        public static List<TEntity> TopN<TEntity>(this EFContext dbcontext, Expression<Func<TEntity, bool>> condition, int topN)
            where TEntity : class, IEntity
        {
            return dbcontext.Set<TEntity>()
                .WhereByVisible(condition).TopN(topN).ToList();
        }

        public static int Count<TEntity>(this EFContext dbcontext, Expression<Func<TEntity, bool>> condition) where TEntity : class, IEntity
        {
            return dbcontext.Set<TEntity>()
                .Count(condition.ByVisible());
        }
    }
}
